<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getResult } from '@/api/search.js'
export default {
  name: 'searchresult',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getResult({
          page: this.page,
          per_page: this.perPage,
          q: this.searchText
        })
        console.log(data)
        const { results } = data.data
        // 模拟错误
        if (Math.random() > 0.5) {
          JSON.parse('fafasafa')
        }

        // this.list.push(...results)
        this.list = [...this.list, ...results]
        // 关闭loading
        this.loading = false
        // 判断是否还有数据
        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        // 展示加载失败的提示
        this.error = true
        // 加载失败了 loading 也要停掉
        this.loading = false
        // this.$toast('获取失败稍后重试')
      }
    }
  }
}
</script>

<style>
</style>
